<?php

/**
 * @package mikrokosmos
 * mk avm2 library file created on  oct-2007
 * dependencies: lib_swf
 * jaco_at_pixeldump_dot_org
 */

//// READ functions

/**
 *
 */
function read_u30($binVal, $requireLength = false){

	$cLength = min(strlen($binVal, 5));
	$binStr = "";

	for($i = 0; $i < $cLength; $i++){
		$b = get_binData_string($binVal[$i]);
		$binStr .= substr($b, 1);
		if($b[0] == "0") break;
	}

	$bLength = strlen($binStr);
	if($bLength > 32) $binStr = substr($binStr, 0, 32);
	else if($bLength < 32){
		$pad = str_repeat("0", 32 - $bLength);
		$binStr = $pad .$binStr;
	}

	$val = hexdec(bin2hex($binVal));

	if($requireLength) {
		$u30 = array();
		$u30["length"] = ++$i;
		$u30["value"] = $val;
	}
	else return $val;
}

/**
 *
 */
function read_constantString ($buf){
	$csLength = ui8dec($buf[0]);
	return substr($buf, 1, $csLength);
}

/**
 *
 */
function read_constantNameSpace($buf){
	$nsd = array();
	$nsd["kind"] = ui8dec($buf[0]);
	$nsd["name_index"] = read_u30(substr($buf, 1));

	return $nsd;
}

/**
 *
 */
function read_constantNameSpaceSet($buf){
	$nssd = array();
	$u30Count = read_u30($buf[0], true);
	$nssd["count"] = $u30Count["value"];
	$nssd["namespaces"] = array();
	$ofst =  $u30Count["value"];

	for($i = 0; $i < $nssd["count"]; $i++){
		$u30NS = array();
		$u30NS = read_u30(substr($buf, $ofst));
		$nssd["namespaces"][] = $u30NS["value"];
		$ofst += $u30NS["length"];
	}

	return $nssd;
}



//// WRITE functions


/**
 *
 */
function write_u30($val){
 	/* TODO */
 	if($val <= 0x7F) return chr($val); // this is the most of cases

	$buf = "";
 	$binStr = decbin($val);
 	$bCount = ceil(strlen($binStr) / 7);
	$binStr = str_pad($binStr, $bCount * 7, '0', PAD_LEFT);

	for($i = 0; $i < $bCount - 1; $i++)
		$buf .= swf_bin("1" .substr($binStr, $i * 7, 7));

	$buf .= swf_bin("0" .substr($binStr, -7, 7));

	return $buf;

}

/**
 *
 */
function write_constantString ($csStr){

	$csBuf = chr(strlen($csStr));
	$csBuf .= $csStr;

	return $csBuf;
}

/**
 *
 */
function write_constantNameSpace($nsd = array()){

	$nsBuf = chr($nsd["kind"]);
	$nsBuf .= write_u30($nsd["name_index"]);

	return $nsBuf;
}



//----------------------------------------- end of lib_avm2
?>